package com.lagou.thread;

import com.lagou.common.RequestNode;
import com.lagou.common.TPMonitorContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 自定义线程池： 每隔5s打印一次最近1分钟内每个方法的TP90、TP99的耗时情况
 *
 * @Author: zhangzhiwei
 * @Date: 2022/3/13 18:15
 */
public class TPMonitorThread implements Runnable {

    private static final Logger log = LoggerFactory.getLogger(TPMonitorThread.class);

    public TPMonitorThread(){
        // 每隔5s打印一次最近1分钟内每个方法的TP90、TP99的耗时情况
        Executors.newSingleThreadScheduledExecutor()
                .scheduleWithFixedDelay(this, 1,5, TimeUnit.SECONDS);
    }

    @Override
    public void run() {
        Map<String, Queue<RequestNode>> map = TPMonitorContainer.getMap();
        Set<Map.Entry<String, Queue<RequestNode>>> entries = map.entrySet();
        // 遍历所有的URL
        for (Map.Entry<String, Queue<RequestNode>> entry : entries) {
            Queue<RequestNode> queue = TPMonitorContainer.getQueue(entry.getKey());
            if(queue.isEmpty()){
                return;
            }
            // 获取队列所有元素，放入list中并排序
            List<Long> list = new ArrayList<>();
            log.info("队列大小：" + queue.size());
            long time1 = System.currentTimeMillis();
            // 注：此处用iterator有bug
            for (RequestNode requestNode : queue) {
                list.add(requestNode.getUseTime());
            }
            long time2 = System.currentTimeMillis();
            //log.info("遍历耗时：" + (time2 - time1));

            Collections.sort(list);

            long time3 = System.currentTimeMillis();
            //log.info("排序耗时：" + (time3 - time2));

            // 计算 TP90、TP99
            int size = list.size();
            int tp90 = (int)(size * 0.9);
            int tp99 = (int)(size * 0.99);
            log.info("1分钟内" + entry.getKey() + "的TP90 = " + list.get(tp90) + ",TP99 = " + list.get(tp99));
        }
        log.info("=====================================================================================================");
    }
}
